package org.ladybug.web.controller.form;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.ladybug.dao.DAOService;
import org.ladybug.service.SearchService;
import org.ladybug.web.controller.model.ModelApplicativo;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

public class CreaProfiloUtenteWizardFormController extends AbstractWizardFormController {
	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		SimpleDateFormat df = (SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.DATE_FIELD, request.getLocale());
		df.applyPattern("dd/MM/yyyy");
		CustomDateEditor ce = new CustomDateEditor(df,true);
		ce.addPropertyChangeListener(new PropertyChangeListener(){

			public void propertyChange(PropertyChangeEvent evt) {
				System.out.println(".propertyChange() "+evt.getPropertyName()+": "+evt.getOldValue()+" --> "+evt.getNewValue());
			}
			
		});
		binder.registerCustomEditor(Date.class, ce);
	}

	SearchService searchService;
	@Override
	protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors, int page) throws Exception {
		String prevStep = request.getParameter("prevstep");
		Map model = new HashMap();
		if(prevStep==null){
			List<ModelApplicativo> applicazioni =(List<ModelApplicativo>) searchService.find(null, null);
			ModelApplicativo m0 = new ModelApplicativo();
			m0.setDescrizione("--seleziona--");
			m0.setIdApplicativo("-1");
			m0.setCodiceApplicativo("");
			Object[] objs = new Object[applicazioni.size()+1];
			objs[0]=m0;
			System.arraycopy(applicazioni.toArray(), 0, objs, 1, applicazioni.size());
			applicazioni = new ArrayList<ModelApplicativo>();
			CollectionUtils.addAll(applicazioni, objs);
			model.put("listaApplicativi", applicazioni);
			
		}
		return model;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

}
